<!--suppress VueUnrecognizedSlot -->
<template>
  <div id="homePage">
    <!-- 搜索框 -->
    <div class="search-bar">
      <a-input-search
        placeholder="从海量图片中搜索"
        v-model:value="searchParams.searchText"
        enter-button="搜索"
        size="large"
        allow-clear
        @search="doSearch"
      />
    </div>
    <a-tabs v-model:activeKey="selectedCategory" type="card" @change="doSearch">
      <a-tab-pane key="all" tab="全部" />
      <a-tab-pane v-for="category in categoryList" :key="category" :tab="category" />
    </a-tabs>
    <div class="tag-bar">
      <span>标签：</span>
      <a-space :size="[0, 8]" wrap>
        <a-checkable-tag
          v-for="(tag, index) in tagList"
          :key="tag"
          v-model:checked="selectedTagList[index]"
          @change="doSearch"
        >
          {{ tag }}
        </a-checkable-tag>
      </a-space>
    </div>
    <!-- 使用封装的瀑布流组件 -->
    <PictureWaterfall :picture-list="dataList" @picture-click="doClickPicture" :lazy-load="true" />
    <div class="loading-status" v-if="loading">
      <a-spin />
      <span style="margin-left: 8px">加载中...</span>
    </div>
    <div class="loading-status" v-if="!loading && !hasMore">
      <span>没有更多数据了</span>
    </div>
    <!-- 添加回到顶部按钮 -->
    <div class="back-to-top" v-show="showBackTop" @click="scrollToTop">
      <a-button type="primary" shape="round">
        <template #icon>
          <up-outlined />
        </template>
      </a-button>
    </div>
  </div>
</template>

<script setup lang="ts">
// 数据
import { computed, nextTick, onMounted, onUnmounted, reactive, ref } from 'vue'
import { UpOutlined } from '@ant-design/icons-vue'
import {
  listPictureTagCategoryUsingGet,
  listPictureVoByPageUsingPost,
} from '@/api/pictureController.ts'
import { message } from 'ant-design-vue/es/components'
import { useRouter } from 'vue-router'
import 'vue-waterfall-plugin-next/dist/style.css'
import PictureWaterfall from '@/components/PictureWaterfall.vue'

const dataList = ref([]) as any
const total = ref<number>(0)
const loading = ref(false)
const categoryList = ref<string[]>([])
const selectedCategory = ref<string>('all')
const tagList = ref<string[]>([])
const selectedTagList = ref<string[]>([])
const hasMore = ref(true)
const router = useRouter()
const showBackTop = ref(false)
// 搜索条件
const searchParams = reactive<API.PictureQueryRequest>({
  current: 1,
  pageSize: 14,
  sortField: 'createTime',
  sortOrder: 'descend',
})

// 添加回到顶部相关方法
const scrollToTop = () => {
  window.scrollTo({
    top: 0,
    behavior: 'smooth',
  })
  // 等待滚动完成后再重置数据并重新加载
  setTimeout(() => {
    // 重置数据
    dataList.value = []
    searchParams.current = 1
    hasMore.value = true
    fetchData()
  }, 600) // 给滚动动画足够的时间完成
}

//获取标签和分类
const getTagAndCategory = async () => {
  try {
    const res = await listPictureTagCategoryUsingGet()
    if (res.data.code === 0 && res.data.data) {
      categoryList.value = res.data.data.categoryList ?? []
      tagList.value = res.data.data.tagList ?? []
    } else {
      message.error('获取标签和分类失败' + res.data.message)
    }
  } catch (error) {
    message.error('获取标签和分类失败')
  }
}

// 分页参数
const pagination = computed(() => {
  return {
    current: searchParams.current ?? 1,
    pageSize: searchParams.pageSize ?? 10,
    total: total.value,
    // 切换页号时，会修改搜索参数并获取数据
    onChange: (page: number, pageSize: number) => {
      searchParams.current = page
      searchParams.pageSize = pageSize
      fetchData()
    },
  }
})

const doSearch = () => {
  // 重置搜索条件
  searchParams.current = 1
  dataList.value = [] // 清空现有数据
  hasMore.value = true // 重置加载状态
  fetchData()
}

const fetchData = async () => {
  if (loading.value || !hasMore.value) return
  const params = {
    ...searchParams,
    tags: [] as string[],
  }
  if (selectedCategory.value !== 'all') {
    params.category = selectedCategory.value
  }
  selectedTagList.value.forEach((tag, index) => {
    if (tag) {
      params.tags.push(tagList.value[index])
    }
  })
  try {
    loading.value = true
    const res = await listPictureVoByPageUsingPost(params)
    if (res.data.data) {
      const newRecords = res.data.data.records ?? []
      if (searchParams.current === 1) {
        dataList.value = newRecords
      } else {
        dataList.value = [...dataList.value, ...newRecords]
      }
      total.value = res.data.data.total ?? 0
      // 判断是否还有更多数据
      hasMore.value = dataList.value.length < total.value
      // 如果有更多数据，增加页码以便下次加载
      if (hasMore.value) {
        searchParams.current!++
      }
    } else {
      message.error('获取图片列表失败' + res.data.message)
    }
  } catch (error) {
    message.error('获取图片列表失败')
  } finally {
    loading.value = false
  }
}

// 监听滚动事件，实现无限滚动
const setupInfiniteScroll = () => {
  const handleScroll = () => {
    const { scrollTop, clientHeight, scrollHeight } = document.documentElement
    // 显示/隐藏回到顶部按钮
    showBackTop.value = scrollTop > clientHeight
    // 基础校验条件
    if (loading.value || !hasMore.value) return
    // 计算滚动位置
    const isNearBottom = scrollHeight - scrollTop - clientHeight < 100
    // 到达阈值时加载数据
    if (isNearBottom) {
      setTimeout(() => {
        fetchData()
      }, 100)
    }
  }
  window.addEventListener('scroll', handleScroll)
  // 返回清理函数
  return () => {
    window.removeEventListener('scroll', handleScroll)
  }
}

onMounted(() => {
  fetchData()
  getTagAndCategory()
  const cleanup = setupInfiniteScroll()

  onUnmounted(() => {
    cleanup()
  })
})

// 跳转至图片详情
const doClickPicture = (picture: API.Picture) => {
  router.push({
    path: `/picture/${picture.id}`,
  })
}
</script>

<style scoped>
#homePage .search-bar {
  max-width: 480px;
  margin: 0 auto 16px;
}

#homePage .tag-bar {
  margin-bottom: 16px;
  margin-left: 10px;
  font-size: 16px;
  gap: 8px;
}

/* 设置可勾选标签的字体样式 */
#homePage .tag-bar :deep(.ant-tag-checkable) {
  font-size: 16px;
  font-weight: 500;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  transition: all 0.2s;
  padding: 4px 12px;
  border-radius: 14px;
}

/* 选中状态的样式 */
#homePage .tag-bar :deep(.ant-tag-checkable-checked) {
  color: #fff;
  background: #1890ff;
}

/* 未选中状态的样式 */
#homePage .tag-bar :deep(.ant-tag-checkable:not(.ant-tag-checkable-checked)) {
  color: #666;
  background: #f5f5f5;
}

/* 添加滚动容器样式 */
.loading-status {
  text-align: center;
  padding: 16px 0;
  color: #999;
  font-size: 14px;
}

/* 回到顶部按钮样式 */
.back-to-top {
  position: fixed;
  right: 40px;
  bottom: 80px;
  cursor: pointer;
  z-index: 999;
  transition: all 0.3s;
}

.back-to-top button {
  width: 50px;
  height: 50px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-to-top:hover {
  transform: translateY(-5px);
}

.back-to-top button:hover {
  box-shadow: 0 8px 20px rgba(24, 144, 255, 0.3);
}

/* 添加数据过渡效果 */
:deep(.waterfall-item) {
  transition: opacity 0.3s ease-in-out;
}

:deep(.waterfall-item-enter-active),
:deep(.waterfall-item-leave-active) {
  transition: opacity 0.3s ease-in-out;
}

:deep(.waterfall-item-enter-from),
:deep(.waterfall-item-leave-to) {
  opacity: 0;
}
</style>
